package com.shop.front.service.user;

import com.alibaba.fastjson.JSON;
import com.shop.domain.user.UserIntegralBill;
import com.shop.front.dao.user.UserIntegralBillDao;
import com.shop.front.dao.user.UserIntegralBillSQLDao;
import com.shop.web.cache.RedisCache;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
@Transactional
public class UserIntegtralBillService {

    @Autowired
    private UserIntegralBillDao userIntegralBillDao;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserIntegralBillSQLDao userIntegralBillSQLDao;


    public BaseResponse getIntegralBillLog(Long storePinkId,Long userId) {
        List<UserIntegralBill> userIntegralBill = null;

        // 首页缓存key
        int cacheTime = 30;  // 秒
        String cacheKey = "getIntegralBillLog_" + userId + "_" + storePinkId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            userIntegralBill = JSON.parseObject(cacheVal, List.class);
            return new BaseResponse(userIntegralBill);
        }

        userIntegralBill = userIntegralBillDao.findAllByLinkIdAndUid(storePinkId,userId);

        // 缓存返回值
        redisCache.set(cacheKey, JSON.toJSONString(userIntegralBill), cacheTime);

        return new BaseResponse(userIntegralBill);
    }


    public BaseResponse getIntegralBills(Long userId) {
        Page page = userIntegralBillSQLDao.pageIntegralBill(userId);
        return new BaseResponse(page);
    }


    /**
     * 增加用户积分记录流水
     * @param userId  用户ID
     * @param linkId  关联ID（拼团订单ID）
     * @param initIntegral  原始积分
     * @param integral  积分
     * @param refreshIntegral  更新后积分
     * @param tableName 业务类型
     * @param pm 流水类型 0收入 1支出
     * @param mark 备注
     * @return
     */
    public BaseResponse addUserIntegralBill(Long userId, Long linkId, BigDecimal initIntegral, BigDecimal integral,BigDecimal refreshIntegral, String tableName,
                                     int pm, String mark) {

        UserIntegralBill userIntegralBill = new UserIntegralBill();
        userIntegralBill.setUid(userId);
        userIntegralBill.setLinkId(linkId);
        userIntegralBill.setInitIntegral(initIntegral);
        userIntegralBill.setIntegral(integral);
        userIntegralBill.setRefreshIntegral(refreshIntegral);
        userIntegralBill.setTableName(tableName);
        userIntegralBill.setPm(pm);
        userIntegralBill.setMark(mark);
        userIntegralBillDao.save(userIntegralBill);

        return new BaseResponse();
    }




}
